import { changeProtocolStatus, getProtocolPage } from '@/apis/system/protocol'
import { BaseData, BaseMethod } from '@/utils/basc-data'
import { ElMessage } from 'element-plus'
import { reactive } from 'vue'
import { channelEnum } from '../edit'
import { tableConfig } from './config'
import router from '@/router'

export class ProtocolData extends BaseData implements BaseMethod {
    //定义预览弹窗显示内容
    dialog = reactive({
        visible: false, //弹窗是否隐藏
        id: '' //协议id
    })

    constructor() {
        console.log(tableConfig)
        super(tableConfig)
        this.getData()
    }
    onOperation = (arg?: any) => {
        console.log(arg)
        const { type, data } = arg
        if (type === 'look') {
            this.dialog.visible = true
            this.dialog.id = data.id
        } else if (type === 'create') {
            router.push({
                path: '/protocol/edit',
                query: { type: 'add' }
            })
        } else if (type === 'switch') {
            changeProtocolStatus({ id: data.id, disable: !data.status ? 1 : 0 }).then((res: any) => {
                if (Number(res.data.code) === 200) {
                    ElMessage.success(Number(data.status) ? '启用成功' : '禁用成功')
                    this.getData()
                }
            })
        }
    }

    getData(code = '') {
        getProtocolPage({
            current: this.pageData.pagination.pageNo,
            size: this.pageData.pagination.pageSize,
            code
        }).then(res => {
            if (Number(res.data.code) === 200) {
                this.pageData.pagination.total = res.data.result.total
                this.pageData.table.data.length = 0
                const arr: any[] = [...res.data.result.records]
                arr.forEach(item => {
                    const arr: string[] = []
                    item.status = Number(item.disable) === 0 ? true : false
                    item.type.split(',').forEach((channel: number) => {
                        arr.push(channelEnum[channel])
                    })
                    item.type = arr.join(',')
                })
                this.pageData.table.data.push(...arr)
            }
        })
    }

    /**
     * 监听点击搜索
     * @param res
     */
    onSearch = (res: any) => {
        this.getData(res.protocolType)
    }

    /**
     * 监听点击重置
     */
    onReset = () => {
        this.pageData.pagination.pageNo = 1
        this.getData()
    }

    /**
     * 监听分页改变
     * @param index
     */
    onPaginationChange = (index: number) => {
        console.log('index', index)
        this.getData()
    }

    /**
     * 监听选择每页显示个数
     * @param size
     */
    onPaginationSize = (size: number) => {
        this.pageData.pagination.pageNo = 1
        this.pageData.pagination.pageSize = size
        this.getData()
    }

    /**
     * 监听预览弹窗显示隐藏
     */
    onDialogHidden = () => {
        this.dialog.visible = false
    }
}
